<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use App\Models\RoleUser;

class DistributionController extends Controller
{
    public function distributionHouse(Request $request) {
        $request_data = $request->input();
        if (!isset($request_data['apartment_application_id']) || !$request_data['apartment_application_id']) {
            return response()->json(['code' => 0, 'message' => '公寓申请ID为必填项']);
        }
        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['remark']) || !$request_data['remark']) {
            return response()->json(['code' => 0, 'message' => '备注为必填项']);
        }
        // TODO 该申请者是否正常

        // TODO 该房号是否正常

        DB::beginTransaction();
        try {
            $room_no_id = trim($request_data['room_no_id']);
            $room_no_data = array(
                'room_status' => 1,
                'distribution_uid' => $request_data['user']['uid'],
                'apartment_application_id' => $request_data['apartment_application_id']
            );
            $house_operate_records_data = array(
                'room_no_id' => $room_no_id,
                'apartment_application_id' => $request_data['apartment_application_id'],
                'operate_status' => 0,
                'operate_uid' => $request_data['user']['uid'],
                'remark' => $request_data['remark']
            );
            $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[59]['regulation']);
            $message = new MessageController();
            foreach ($user_ids as $key => $uid) {
                $message->addMessage($uid->user_id, 59, '房源已分配待入住');
            }
            $room_no_info = DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->first();
            $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
            $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
            $house = $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no;
            $application_info = DB::table('apartment_application')->where('apartment_application_id', $request_data['apartment_application_id'])->first();
            (new MessageController())->addMessage($application_info->user_id, 63, "已为您分配".$house."房号");
            if (DB::table('apartment_application')->where('apartment_application_id', $request_data['apartment_application_id'])->update(array('is_distribution' => 1)) && DB::table('room_no')->where('room_no_id', $room_no_id)->update($room_no_data) && DB::table('house_operate_records')->insert($house_operate_records_data)) {
                DB::commit();
                return response()->json(['code' => 1, 'message' => '分配成功']);
            } else {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '分配失败']);
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '分配失败']);
        }
    }

    public function distributionHouses(Request $request) {
        $request_data = $request->input();
        $user_keywords = '';
        $approval_start_time = '';
        $approval_end_time = '';
        if (isset($request_data['user_keywords'])) {
            $user_keywords = $request_data['user_keywords'];
        }
        if (isset($request_data['approval_start_time'])) {
            $approval_start_time = $request_data['approval_start_time'];
        }
        if (isset($request_data['approval_end_time'])) {
            $approval_end_time = $request_data['approval_end_time'];
        }$page_size = 10;
        if (isset($request_data['page_size'])) {
            $page_size = $request_data['page_size'];
        }
        $sql = "SELECT ra.apartment_application_id, ra.real_name, ra.phone, ra.idcard, ra.unit_name, rac.approval_uid, rac.add_time as approval_time FROM rcjh_apartment_application ra, rcjh_apartment_approval_records rac WHERE ra.apartment_application_id = rac.apartment_application_id AND ra.approval_status = 4 AND ra.is_distribution = 0 AND rac.stage = 2 AND rac.approval_result = 1";
        if ($user_keywords) {
            $sql .= " AND (ra.real_name LIKE '%$user_keywords%' OR ra.phone LIKE '%$user_keywords%')";
        }
        if ($approval_start_time) {
            $sql .= " AND rac.add_time > '$approval_start_time'";
        }
        if ($approval_end_time) {
            $sql .= " AND rac.add_time < '$approval_end_time'";
        }
        $sql .= " ORDER BY rac.add_time DESC";
        $response_data = DB::table(DB::raw("($sql limit 9999999) as apartment_application"))->Paginate($page_size);
        foreach ($response_data as $key => $value) {
            $approval_name = DB::table('admins')->where('id', $value->approval_uid)->value('name');
            $response_data[$key]->approval_name = $approval_name ? $approval_name : '';
        }

        return response()->json(['code' => 1, 'data' => $response_data]);
    }

    public function distributionRoomNoList(Request $request) {
        $request_data = $request->input();
        $user_keywords = '';
        $community_id = 0;
        $building_id = 0;
        $units = '';
        $room_no_id = 0;
        $distribution_start_time = '';
        $distribution_end_time = '';
        $room_status = 1;
        if (isset($request_data['user_keywords'])) {
            $user_keywords = $request_data['user_keywords'];
        }
        if (isset($request_data['community_id'])) {
            $community_id = $request_data['community_id'];
        }
        if (isset($request_data['building_id'])) {
            $building_id = $request_data['building_id'];
        }
        if (isset($request_data['units'])) {
            $units = $request_data['units'];
        }
        if (isset($request_data['room_no_id'])) {
            $room_no_id = $request_data['room_no_id'];
        }
        if (isset($request_data['distribution_start_time'])) {
            $distribution_start_time = $request_data['distribution_start_time'];
        }
        if (isset($request_data['distribution_end_time'])) {
            $distribution_end_time = $request_data['distribution_end_time'];
        }
        if (isset($request_data['room_status'])) {
            $room_status = $request_data['room_status'];
        }
        $page_size = 10;
        if (isset($request_data['page_size'])) {
            $page_size = $request_data['page_size'];
        }

        if ($room_status != 0) {
            $sql = "SELECT rr.room_no_id, rr.room_no, rr.community_id, rr.building_id, ra.real_name, ra.phone, ra.idcard, ra.unit_name, rr.distribution_uid, rr.room_status, rr.modify_time, rr.lease_period_start_time, rr.lease_period_end_time, rr.units, rr.floors FROM rcjh_room_no rr, rcjh_apartment_application ra WHERE rr.apartment_application_id = ra.apartment_application_id AND rr.room_status = $room_status AND ra.is_give_up = 0";
            if ($user_keywords) {
                $sql .= " AND (ra.real_name LIKE '%$user_keywords%' OR ra.phone LIKE '%$user_keywords%')";
            }
            if ($community_id) {
                $sql .= " AND rr.community_id = $community_id";
            }
            if ($building_id) {
                $sql .= " AND rr.building_id = $building_id";
            }
            if ($units) {
                $sql .= " AND rr.units = '$units'";
            }
            if ($room_no_id) {
                $sql .= " AND rr.room_no_id = $room_no_id";
            }
            // 已分配（筛选分配时间）
            if ($room_status == 1) {
                if ($distribution_start_time) {
                    $sql .= " AND rr.modify_time > '$distribution_start_time'";
                }
                if ($distribution_end_time) {
                    $sql .= " AND rr.modify_time < '$distribution_end_time'";
                }
                $sql .= " ORDER BY rr.modify_time DESC";
            }
            // 已出租（筛选入住时间）
            if ($room_status == 2) {
                if ($distribution_start_time) {
                    $sql .= " AND rr.lease_period_start_time > '$distribution_start_time'";
                }
                if ($distribution_end_time) {
                    $sql .= " AND rr.lease_period_end_time < '$distribution_end_time'";
                }
            }
        } else {
            $sql = "SELECT room_no_id, room_no, community_id, building_id, room_status, units, floors, distribution_uid FROM rcjh_room_no WHERE room_status = $room_status AND status = 1";
            if ($community_id) {
                $sql .= " AND community_id = $community_id";
            }
            if ($building_id) {
                $sql .= " AND building_id = $building_id";
            }
            if ($units) {
                $sql .= " AND units = '$units'";
            }
            if ($room_no_id) {
                $sql .= " AND room_no_id = $room_no_id";
            }
        }
        $response_data = DB::table(DB::raw("($sql limit 9999999) as rcjh_room_no"))->Paginate($page_size);
        $response_data = $response_data ? $response_data : array();
        foreach ($response_data as $key => $value) {
            $community_name = DB::table('community')->where('community_id', $value->community_id)->value('community_name');
            $building_info = DB::table('building')->where('building_id', $value->building_id)->first(['buildings', 'unit']);
            $approval_name = DB::table('admins')->where('id', $value->distribution_uid)->value('name');
            $response_data[$key]->distribution_name = $approval_name ? $approval_name : '';
            $response_data[$key]->community_name = $community_name ? $community_name : '';
            $response_data[$key]->building = $building_info ? $building_info->buildings.$building_info->unit : '';
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
    }

    public function giveUpApplicationList(Request $request) {
        $request_data = $request->input();
        $user_keywords = '';
        $community_id = 0;
        $building_id = 0;
        $units = '';
        $room_no_id = 0;
        $distribution_start_time = '';
        $distribution_end_time = '';
        if (isset($request_data['user_keywords'])) {
            $user_keywords = $request_data['user_keywords'];
        }
        if (isset($request_data['community_id'])) {
            $community_id = $request_data['community_id'];
        }
        if (isset($request_data['building_id'])) {
            $building_id = $request_data['building_id'];
        }
        if (isset($request_data['units'])) {
            $units = $request_data['units'];
        }
        if (isset($request_data['room_no_id'])) {
            $room_no_id = $request_data['room_no_id'];
        }
        if (isset($request_data['distribution_start_time'])) {
            $distribution_start_time = $request_data['distribution_start_time'];
        }
        if (isset($request_data['distribution_end_time'])) {
            $distribution_end_time = $request_data['distribution_end_time'];
        }
        $page_size = 10;
        if (isset($request_data['page_size'])) {
            $page_size = $request_data['page_size'];
        }

        $sql = "SELECT rr.room_no_id, rr.room_no, rr.community_id, rr.building_id, ra.real_name, ra.phone, ra.idcard, ra.unit_name, rr.distribution_uid, rr.modify_time, rr.units, rr.floors, rh.house_operate_record_id, rh.add_time as give_up_time, rh.remark FROM rcjh_room_no rr, rcjh_apartment_application ra, rcjh_house_operate_records rh WHERE rr.apartment_application_id = ra.apartment_application_id AND rr.room_no_id = rh.room_no_id AND rr.room_status = 1 AND rh.operate_status = 1 AND rh.operate_uid = 0";
        if ($user_keywords) {
            $sql .= " AND (ra.real_name LIKE '%$user_keywords%' OR ra.phone LIKE '%$user_keywords%')";
        }
        if ($community_id) {
            $sql .= " AND rr.community_id = $community_id";
        }
        if ($building_id) {
            $sql .= " AND rr.building_id = $building_id";
        }
        if ($units) {
            $sql .= " AND rr.units = '$units'";
        }
        if ($room_no_id) {
            $sql .= " AND rr.room_no_id = $room_no_id";
        }
        if ($distribution_start_time) {
            $sql .= " AND rh.add_time > '$distribution_start_time'";
        }
        if ($distribution_end_time) {
            $sql .= " AND rh.add_time < '$distribution_end_time'";
        }
        $sql .= " ORDER BY rh.add_time DESC";
        $response_data = DB::table(DB::raw("($sql limit 9999999) as rcjh_room_no"))->Paginate($page_size);
        $response_data = $response_data ? $response_data : array();
        foreach ($response_data as $key => $value) {
            $community_name = DB::table('community')->where('community_id', $value->community_id)->value('community_name');
            $building_info = DB::table('building')->where('building_id', $value->building_id)->first(['buildings', 'unit']);
            $approval_name = DB::table('admins')->where('id', $value->distribution_uid)->value('name');
            $response_data[$key]->distribution_name = $approval_name ? $approval_name : '';
            $response_data[$key]->community_name = $community_name ? $community_name : '';
            $response_data[$key]->building = $building_info ? $building_info->buildings.$building_info->unit : '';
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
    }

    public function changeRoomApplicationList(Request $request) {
        $request_data = $request->input();
        $user_keywords = '';
        $start_time = '';
        $end_time = '';
        if (isset($request_data['user_keywords'])) {
            $user_keywords = $request_data['user_keywords'];
        }
        if (isset($request_data['start_time'])) {
            $start_time = $request_data['start_time'];
        }
        if (isset($request_data['end_time'])) {
            $end_time = $request_data['end_time'];
        }
        $page_size = 10;
        if (isset($request_data['page_size'])) {
            $page_size = $request_data['page_size'];
        }

        $sql = "SELECT rr.room_no_id, rr.room_no, rr.community_id, rr.building_id, ra.real_name, ra.phone, ra.idcard, ra.unit_name, rr.distribution_uid, rr.modify_time, rr.units, rr.floors, rh.change_room_application_id, rh.remark, rh.photos FROM rcjh_room_no rr, rcjh_apartment_application ra, rcjh_change_room_application_records rh WHERE rr.apartment_application_id = ra.apartment_application_id AND rr.room_no_id = rh.room_no_id AND rh.approval_status = 0";
        if ($user_keywords) {
            $sql .= " AND (ra.real_name LIKE '%$user_keywords%' OR ra.phone LIKE '%$user_keywords%')";
        }
        if ($start_time) {
            $sql .= " AND rh.add_time > '$start_time'";
        }
        if ($end_time) {
            $sql .= " AND rh.add_time < '$end_time'";
        }
        $sql .= " ORDER BY rh.add_time DESC";
        $response_data = DB::table(DB::raw("($sql limit 9999999) as rcjh_room_no"))->Paginate($page_size);
        $response_data = $response_data ? $response_data : array();
        foreach ($response_data as $key => $value) {
            $community_name = DB::table('community')->where('community_id', $value->community_id)->value('community_name');
            $building_info = DB::table('building')->where('building_id', $value->building_id)->first(['buildings', 'unit']);
            $approval_name = DB::table('admins')->where('id', $value->distribution_uid)->value('name');
            $response_data[$key]->distribution_name = $approval_name ? $approval_name : '';
            $response_data[$key]->community_name = $community_name ? $community_name : '';
            $response_data[$key]->building = $building_info ? $building_info->buildings.$building_info->unit : '';
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
    }

    public function distributionCheckin(Request $request) {
        $request_data = $request->input();
        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['lease_period_start_time']) || !$request_data['lease_period_start_time']) {
            return response()->json(['code' => 0, 'message' => '租期开始时间为必填项']);
        }
        if (!isset($request_data['lease_period_end_time']) || !$request_data['lease_period_end_time']) {
            return response()->json(['code' => 0, 'message' => '租期结束时间为必填项']);
        }
        $room_no_info = DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->first();
        if (!$room_no_info) {
            return response()->json(['code' => 0, 'message' => '获取房源信息失败']);
        }

        DB::beginTransaction();
        try {
            $room_no_id = trim($request_data['room_no_id']);
            $room_no_data = array(
                'room_status' => 2,
                'distribution_uid' => $request_data['user']['uid'],
                'lease_period_start_time' => $request_data['lease_period_start_time'],
                'lease_period_end_time' => $request_data['lease_period_end_time']
            );
            $house_operate_records_data = array(
                'room_no_id' => $room_no_id,
                'operate_status' => 3,
                'apartment_application_id' => $room_no_info->apartment_application_id,
                'operate_uid' => $request_data['user']['uid'],
                'start_time' => $request_data['lease_period_start_time'],
                'end_time' => $request_data['lease_period_end_time']
            );
            $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
            $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
            $house = $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no;
            $application_info = DB::table('apartment_application')->where('apartment_application_id', $room_no_info->apartment_application_id)->first();
            (new MessageController())->addMessage($application_info->user_id, 68, "您在".$house."房号已入住");
            if (DB::table('room_no')->where('room_no_id', $room_no_id)->update($room_no_data) && DB::table('house_operate_records')->insert($house_operate_records_data)) {
                DB::commit();
                return response()->json(['code' => 1, 'message' => '操作成功']);
            } else {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '操作失败']);
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '操作失败']);
        }
    }

    public function distributionFree(Request $request) {
        $request_data = $request->input();
        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['house_operate_record_id']) || !$request_data['house_operate_record_id']) {
            return response()->json(['code' => 0, 'message' => '放弃入住ID为必填项']);
        }
        $room_no_info = DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->first();
        if (!$room_no_info) {
            return response()->json(['code' => 0, 'message' => '获取房源信息失败']);
        }

        DB::beginTransaction();
        try {
            $room_no_id = trim($request_data['room_no_id']);
            $room_no_data = array(
                'room_status' => 0,
                'distribution_uid' => $request_data['user']['uid'],
                'apartment_application_id' => 0,
                'lease_period_start_time' => null,
                'lease_period_end_time' => null
            );
            $house_operate_records_data = array(
                'operate_uid' => $request_data['user']['uid']
            );
            $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[64]['regulation']);
            $message = new MessageController();
            foreach ($user_ids as $key => $uid) {
                $message->addMessage($uid->user_id, 64, '房源已放弃，可重新分配');
            }
            $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
            $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
            $house = $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no;
            $application_info = DB::table('apartment_application')->where('apartment_application_id', $room_no_info->apartment_application_id)->first();
            (new MessageController())->addMessage($application_info->user_id, 69, "您在".$house."房号已放弃入住");
            if (DB::table('room_no')->where('room_no_id', $room_no_id)->update($room_no_data) && DB::table('house_operate_records')->where('house_operate_record_id', $request_data['house_operate_record_id'])->update($house_operate_records_data)) {
                DB::commit();
                return response()->json(['code' => 1, 'message' => '操作成功']);
            } else {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '操作失败']);
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '操作失败']);
        }
    }

    public function changeRoomApproval(Request $request) {
        $request_data = $request->input();
        if (!isset($request_data['change_room_application_id']) || !$request_data['change_room_application_id']) {
            return response()->json(['code' => 0, 'message' => '换房ID为必填项']);
        }
        if (!isset($request_data['approval_status']) || !$request_data['approval_status']) {
            return response()->json(['code' => 0, 'message' => '审核状态为必填项']);
        }
        if (!isset($request_data['remark']) || !$request_data['remark']) {
            return response()->json(['code' => 0, 'message' => '备注为必填项']);
        }
        if ($request_data['approval_status'] == 1 && (!isset($request_data['room_no_id']) || !$request_data['room_no_id'])) {
            return response()->json(['code' => 0, 'message' => '重新分配房号ID为必填项']);
        }

        DB::beginTransaction();
        try {
            $change_room_info = DB::table('change_room_application_records')->where('change_room_application_id', $request_data['change_room_application_id'])->first();
            if (!$change_room_info) {
                return response()->json(['code' => 0, 'message' => '获取换房信息失败']);
            }
            $room_no_info = DB::table('room_no')->where('apartment_application_id', $change_room_info->apartment_application_id)->first();
            if (!$room_no_info) {
                return response()->json(['code' => 0, 'message' => '获取房源信息失败']);
            }
            if ($request_data['approval_status'] == 1) {
                $new_room_no_info = DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->first();
                if (!$new_room_no_info) {
                    return response()->json(['code' => 0, 'message' => '获取房源信息失败']);
                }
                $new_room_no_id = trim($request_data['room_no_id']);
                $room_no_data = array(
                    'room_status' => 0,
                    'distribution_uid' => 0,
                    'apartment_application_id' => 0,
                    'lease_period_start_time' => null,
                    'lease_period_end_time' => null
                );
                $new_room_no_data = array(
                    'room_status' => 1,
                    'distribution_uid' => $request_data['user']['uid'],
                    'apartment_application_id' => $change_room_info->apartment_application_id,
                );
                $house_operate_records_data = array(
                    'room_no_id' => $new_room_no_id,
                    'apartment_application_id' => $change_room_info->apartment_application_id,
                    'operate_status' => 0,
                    'operate_uid' => $request_data['user']['uid'],
                    'remark' => $request_data['remark']
                );
                if (DB::table('room_no')->where('room_no_id', $room_no_info->room_no_id)->update($room_no_data) && DB::table('room_no')->where('room_no_id', $new_room_no_id)->update($new_room_no_data) && DB::table('house_operate_records')->insert($house_operate_records_data) && DB::table('change_room_application_records')->where('change_room_application_id', $request_data['change_room_application_id'])->update(array('approval_status' => $request_data['approval_status'], 'operate_uid' => $request_data['user']['uid'], 'approval_reason' => $request_data['remark'], 'new_room_no_id' => $new_room_no_id))) {
                    DB::commit();
                    return response()->json(['code' => 1, 'message' => '操作成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code' => 0, 'message' => '操作失败']);
                }
            } else {
                if (DB::table('change_room_application_records')->where('change_room_application_id', $request_data['change_room_application_id'])->update(array('approval_status' => $request_data['approval_status'], 'operate_uid' => $request_data['user']['uid'], 'approval_reason' => $request_data['remark']))) {
                    DB::commit();
                    return response()->json(['code' => 1, 'message' => '操作成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code' => 0, 'message' => '操作失败']);
                }
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '操作失败']);
        }
    }
}